﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;

namespace ManhattanProcedure.Model
{
    /// <summary>
    /// 咖啡机io板通讯
    /// </summary>
    public class CoffeeIOMsg
    {
        private static CoffeeIOMsg instance;
        private CoffeeIOMsg() { }
        public static CoffeeIOMsg Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new CoffeeIOMsg();
                }
                return instance;
            }
        }
        #region IO通讯
        public bool AllBol = true;
        public bool RobotBol = true;
        public delegate void IOdelegate(string btnName, string tag);
        public IOdelegate iodelegate;
        /// <summary>
        ///  IO的通讯返回数据
        /// </summary>
        private List<byte> buffer = new List<byte>();
        public static bool IsMsgError = true;
        string nostrs = "";
        public Thread All_thr;
        public void QK()
        {
            try
            {
                CoffeeIOMsg.Instance.AllBol = false;
                Thread.Sleep(100);
                CoffeeIOSerialPort.Instance.SerialSend(CoffeeIOModel.Instance.KSZZ_Robot_Left_End);
                Thread.Sleep(100);
                CoffeeIOSerialPort.Instance.SerialSend(CoffeeIOModel.Instance.QB_Robot_Left_End);
                Thread.Sleep(100);
                CoffeeIOSerialPort.Instance.SerialSend(CoffeeIOModel.Instance.BJC_Robot_Left_End);
                Thread.Sleep(100);
                CoffeeIOSerialPort.Instance.SerialSend(CoffeeIOModel.Instance.JKF_Robot_Left_End);
                Thread.Sleep(100);
                CoffeeIOSerialPort.Instance.SerialSend(CoffeeIOModel.Instance.KFWC_Robot_Left_End);
                Thread.Sleep(100);
                CoffeeIOSerialPort.Instance.SerialSend(CoffeeIOModel.Instance.QDY_Robot_Left_End);
                Thread.Sleep(100);
                CoffeeIOSerialPort.Instance.SerialSend(CoffeeIOModel.Instance.DYWC_Robot_Left_End);
                Thread.Sleep(100);
                CoffeeIOSerialPort.Instance.SerialSend(CoffeeIOModel.Instance.CB_Robot_Left_End);
                Thread.Sleep(100);
                CoffeeIOSerialPort.Instance.SerialSend(CoffeeIOModel.Instance.JBCG_Robot_Left_End);
                Thread.Sleep(100);
                CoffeeIOSerialPort.Instance.SerialSend(CoffeeIOModel.Instance.JBSB_Robot_Left_End);
                Thread.Sleep(100);
                CoffeeIOSerialPort.Instance.SerialSend(CoffeeIOModel.Instance.BKF_Robot_Left_End);
                Thread.Sleep(100);
                CoffeeIOSerialPort.Instance.SerialSend(CoffeeIOModel.Instance.DYKF_Robot_Left_End);
                Thread.Sleep(100);
                CoffeeIOSerialPort.Instance.SerialSend(CoffeeIOModel.Instance.LHKF_Robot_Left_End);
                Thread.Sleep(100);
                CoffeeIOSerialPort.Instance.SerialSend(CoffeeIOModel.Instance.LHCC_Robot_Left_End);
                Thread.Sleep(100);
                CoffeeIOSerialPort.Instance.SerialSend(CoffeeIOModel.Instance.GT_Robot_Left_End);
                Thread.Sleep(100);
                CoffeeIOSerialPort.Instance.SerialSend(CoffeeIOModel.Instance.GTWC_Robot_Left_End);
                Thread.Sleep(100);
                CoffeeIOMsg.Instance.AllBol = true;
            }
            catch (Exception)
            {
                return;
            }
        }
        public void IOSerial_Thr()
        {
            try
            {
                var ddd = SerialPort.GetPortNames().ToList();
                if (!SerialPort.GetPortNames().ToList().Any(a => a.ToLower().Contains(IPorPortInfo.Instance.IOCoffeePortName)))
                {
                    Thread.Sleep(1000);
                    IOSerial_Thr();
                }
                CoffeeIOSerialPort.Instance.IceMachineConnect(IPorPortInfo.Instance.IOCoffeePortName, 38400, "", 8, 1);//其他串口通讯
                CoffeeIOSerialPort.Instance.serialPort.DataReceived += SerialPort_DataReceived;
                Robot_Thr();
                All_thr = new Thread(AllMessages);
                All_thr.IsBackground = true;
                All_thr.Start();
            }
            catch (Exception)
            {
                CoffeeIOSerialPort.Instance.serialPort.DataReceived -= SerialPort_DataReceived;
                Thread.Sleep(100);
                IOSerial_Thr();
            }
        }
        public void Robot_Thr()
        {
            try
            {
                RobotOperate.Read_CSV(); //读取轨迹文件
                RobotOperate.Instance.Robot_Initialisation_double(); //机器人初始化
            }
            catch (Exception)
            {
                Thread.Sleep(100);
                Robot_Thr();
            }
        }
        /// <summary>
        /// PING 通 IP
        /// </summary>
        /// <param name="IP"></param>
        /// <returns></returns>
        public bool PingIP(string IP)
        {
            try
            {
                if (IP.Split('.').Count() < 4) return false;
                Ping pingSender = new Ping();
                PingReply reply = pingSender.Send(IP, 120);//第一个参数为ip地址，第二个参数为ping的时间
                if (reply.Status == IPStatus.Success)
                {
                    return true;
                }
                else
                {
                    //ping不通
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

        public void AllMessages()
        {
            try
            {
                while (true)
                {
                    try
                    {
                        if (Instance.AllBol)
                            CoffeeIOSerialPort.Instance.SerialSend(CoffeeIOModel.Instance.AllMessage);
                        Thread.Sleep(100);
                    }
                    catch (Exception)
                    {
                        Thread.Sleep(100);
                    }

                }
            }
            catch (Exception)
            {
                CoffeeIOSerialPort.Instance.serialPort.DataReceived -= SerialPort_DataReceived;
                Thread.Sleep(100);
                IOSerial_Thr();
            }
        }
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                var dd = CoffeeIOSerialPort.Instance.serialPort.BytesToRead;
                byte[] result = new byte[dd];
                CoffeeIOSerialPort.Instance.serialPort.Read(result, 0, dd);
                string str = "";// $"{DateTime.Now}：\n";
                str += $"{Encoding.ASCII.GetString(result)}";
                for (int i = 0; i < result.Length; i++)
                {
                    str += $"{result[i].ToString("X2")} ";
                }
                MsgShow(str);
                Thread.Sleep(1);
            }
            catch (Exception)
            {
                return;
            }
        }
        public void CoffeeIOModelBol2(string str)
        {
            try
            {
                Console.WriteLine(str);
                Console.WriteLine(str[42].ToString());
                Console.WriteLine(str[40].ToString());
                Console.WriteLine(str.Length);
                var Bol = str.Split(' ');
                bool bol = false;
                bool isEmail = false;
                if (WuLiaoCoffeeSel.Instance.BANNER_Sel_Bol != (Bol[4] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.BANNER_Sel_Bol = Bol[4] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.OutMealCup_Sel_Bol != (Bol[10] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.OutMealCup_Sel_Bol = Bol[10] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.PushRodUP_Sel_Bol != (Bol[6] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.PushRodUP_Sel_Bol = Bol[6] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.PushRodDown_Sel_Bol != (Bol[8] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.PushRodDown_Sel_Bol = Bol[8] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.TakeCup_Sel_Bol != (Bol[12] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.TakeCup_Sel_Bol = Bol[12] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.LBQFK1_Bol != (Bol[14] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.LBQFK1_Bol = Bol[14] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.CupFeed1_Sel_Bol != (Bol[22] == "01" ? true : false))
                {
                    if (WuLiaoCoffeeSel.Instance.CupFeed1_Sel_Bol)
                        isEmail = true;
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.CupFeed1_Sel_Bol = Bol[22] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.Milk_Sel_Bol != (Bol[18] == "01" ? true : false))
                {
                    if (WuLiaoCoffeeSel.Instance.Milk_Sel_Bol)
                        isEmail = true;
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.Milk_Sel_Bol = Bol[18] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.Water_Sel_Bol != (Bol[20] == "01" ? true : false))
                {
                    bol = true;
                }
                WuLiaoCoffeeSel.Instance.Water_Sel_Bol = Bol[20] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.Milk_YBJ_Sel_Bol != (Bol[34] == "01" ? true : false))
                {
                    if (WuLiaoCoffeeSel.Instance.Milk_YBJ_Sel_Bol)
                        isEmail = true;
                }
                WuLiaoCoffeeSel.Instance.Milk_YBJ_Sel_Bol = Bol[34] == "01" ? true : false;
                if (WuLiaoCoffeeSel.Instance.Water_YBJ_Sel_Bol != (Bol[32] == "01" ? true : false))
                {
                    if (WuLiaoCoffeeSel.Instance.Water_YBJ_Sel_Bol)
                        isEmail = true;
                }
                WuLiaoCoffeeSel.Instance.Water_YBJ_Sel_Bol = Bol[32] == "01" ? true : false;
                if (isEmail)
                {
                    TestDelegateInvoke testDelegate = new TestDelegateInvoke(DelegateInvokeMethod);
                    testDelegate.BeginInvoke(null, null);
                }
                if (bol)
                {
                    ClientList clientList = new ClientList();
                    clientList.MsgBol = WuLiaoCoffeeSel.Instance;
                    clientList.code = 2;
                    SocketClients.Instance.client.Send(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(clientList)));
                }
            }
            catch (Exception)
            {
                return;
            }
        }
        public delegate void TestDelegateInvoke();

        private void DelegateInvokeMethod()
        {
            try
            {
                EmailShow emailShow = new EmailShow();
                emailShow.content = MainWindow.EmailError();
                var saves1 = JsonConvert.SerializeObject(emailShow);
                Console.WriteLine(emailShow.content);
                var dd1 = HttpMsg.Instance.sendEmailMsg(saves1);
            }
            catch (Exception)
            {
                return;
            }
        }
        string strlist = "";
        public void MsgShow(string str)
        {
            try
            {
                // Console.WriteLine(str);
                nostrs = "";
                var nostr = str.Split(' ');
                nostrs += nostr[0].Substring(nostr[0].Length - 2, 2) + " ";
                for (int i = 1; i < nostr.Count() - 1; i++)
                {
                    nostrs += nostr[i] + " ";
                }
                if (nostrs.Substring(0, 5) == "01 05")
                {
                    Console.WriteLine(str);
                }
                else if (nostrs.Substring(0, 5) == "02 04")
                {
                    strlist = nostrs;
                }
                else if (nostrs.Substring(0, 5) == "04 02")
                {
                    Console.WriteLine(nostrs);
                    var robstr = nostrs.Split(' ');
                    RobotBol = robstr[3] == "01" ? true : false;
                    Console.WriteLine(robstr[3] == "01" ? true : false);
                }
                else
                {
                    if (strlist != "")
                        strlist += nostrs;
                }
                if (strlist.Split(' ').Count() >= 105)
                {
                    CoffeeIOModelBol2(strlist);
                    strlist = "";
                }
            }
            catch (Exception)
            {
                return;
            }
        }
        #region 完整的
        //public void MsgShow(string str)
        //{
        //    try
        //    {
        //         Console.WriteLine(str);
        //        int count = str.Length / 315;
        //        if (count > 0)
        //        {
        //            var str1 = str.Substring(str.Length - count * 315, 315);
        //            //Console.WriteLine(str1);
        //            if (str1.Split(' ').Count() == 105)
        //            {
        //                CoffeeIOModelBol2(str1);
        //                if (count > 1)
        //                    MsgShow(str.Substring(str.Length - (count - 1) * 315, (count - 1) * 315));
        //                strlist = "";
        //            }
        //            else
        //            {
        //                var nostr = str1.Split(' ');
        //                int cc = int.TryParse(nostr[0].Substring(nostr[0].Length - 2, 2), out int a) ? a : -1;
        //                if (cc != -1)
        //                {
        //                    nostrs += nostr[0].Substring(nostr[0].Length - 2, 2) + " ";
        //                    for (int i = 1; i < nostr.Count() - 1; i++)
        //                    {
        //                        nostrs += nostr[i] + " ";
        //                    }
        //                    // Console.WriteLine(nostrs);
        //                    if (nostrs.Substring(0, 5) == "02 04")
        //                    {
        //                        if (nostrs.Count() >= 315)
        //                        {
        //                            CoffeeIOModelBol2(nostrs);
        //                            nostrs = "";
        //                            strlist = "";
        //                        }
        //                        else
        //                        {
        //                            strlist += nostrs;
        //                            if (strlist.Length >= 315)
        //                            {
        //                                CoffeeIOModelBol2(strlist);
        //                                nostrs = "";
        //                                strlist = "";
        //                            }
        //                        }
        //                    }
        //                    else
        //                    {
        //                        nostrs = "";
        //                    }
        //                }
        //            }
        //        }
        //        else
        //        {
        //            var nostr = str.Split(' ');
        //            nostrs += nostr[0].Substring(nostr[0].Length - 2, 2) + " ";
        //            for (int i = 1; i < nostr.Count() - 1; i++)
        //            {
        //                nostrs += nostr[i] + " ";
        //            }
        //            // Console.WriteLine(nostrs);
        //            if (nostrs.Substring(0, 5) == "02 04")
        //            {
        //                //if (nostrs.Count() >= 315)
        //                //{

        //                //    CoffeeIOModelBol2(nostrs);
        //                //    nostrs = "";
        //                //}
        //                if (nostrs.Count() >= 315)
        //                {
        //                    CoffeeIOModelBol2(nostrs);
        //                    nostrs = "";
        //                    strlist = "";
        //                }
        //                else
        //                {
        //                    strlist += nostrs;
        //                    if (strlist.Length >= 315)
        //                    {
        //                        CoffeeIOModelBol2(strlist);
        //                        nostrs = "";
        //                        strlist = "";
        //                    }
        //                }
        //            }
        //            else
        //            {
        //                if (nostrs.Substring(0, 5) == "01 05")
        //                {
        //                    Console.WriteLine(str);
        //                }
        //                else if (nostrs.Substring(0, 5) == "02 04")
        //                {
        //                    // Console.WriteLine(nostrs);
        //                    if (nostrs.Contains("02 04 02 00 01 3C F0"))
        //                    {
        //                        //  CoffeeIOModelBol.Instance.JBCGJC_Bol = true;
        //                    }
        //                }
        //                else if (nostrs.Substring(0, 5) == "03 02")
        //                {
        //                    Console.WriteLine(nostrs);
        //                    var robstr = nostrs.Split(' ');
        //                    RobotBol = robstr[3] == "01" ? true : false;
        //                    Console.WriteLine(robstr[3] == "01" ? true : false);
        //                }
        //                else
        //                {
        //                    strlist += nostrs;
        //                }
        //                nostrs = "";
        //            }
        //        }

        //    }
        //    catch (Exception)
        //    {
        //        return;
        //    }
        //}
        #endregion

        #endregion
    }
}
